package com.nineclock.system.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nineclock.system.emp.Emp;
import com.nineclock.system.emp.EmpParseListener;
import com.nineclock.common.entity.PageResult;
import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.CurrentUserHolder;
import com.nineclock.system.mapper.SysCompanyUserMapper;
import com.nineclock.system.pojo.SysCompanyUser;
import com.nineclock.system.pojo.SysDepartment;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SysCompanyUserService;
import com.nineclock.system.service.SysDepartmentService;
import com.nineclock.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional
@Slf4j
@Service
public class SysCompanyUserServiceImpl extends ServiceImpl<SysCompanyUserMapper, SysCompanyUser> implements SysCompanyUserService {

    @Autowired
    private SysCompanyUserMapper sysCompanyUserMapper;

    /**
     * 思路：
     * 1.获取当前登录用户的公司ID
     * 2.根据公司ID查询到主用户
     * 3.如果判断为空则抛异常
     * 4.响应数据
     */
    @Override
    public SysCompanyUser findCurrentAdmin() {

        //获取登录用户的公司ID
        Long companyId = CurrentUserHolder.get().getCompanyId();

        //查询主管理员
        SysCompanyUser sysCompanyUser = sysCompanyUserMapper.findCurrentAdmin(companyId);

        //判断是否为空
        if (sysCompanyUser == null) {
            throw new NcException(ResponseEnum.COMPANY_ADMIN_NOT_EXISTS);
        }

        //响应数据
        return sysCompanyUser;
    }


    @Override
    public List<SysCompanyUser> findAllUser() {

        //1.获取当前登录用户的公司ID
        Long companyId = CurrentUserHolder.get().getCompanyId();

        //2.查询公司下的所有员工，状态可用
        LambdaQueryWrapper<SysCompanyUser> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(SysCompanyUser::getCompanyId, companyId);
        lambdaQueryWrapper.eq(SysCompanyUser::getEnable, 1);

        //3.查询数据列表
        List<SysCompanyUser> sysCompanyUserList = this.list(lambdaQueryWrapper);

        //4.判断数据如果不存在就抛异常
        if (CollectionUtil.isEmpty(sysCompanyUserList)) {
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }

        //5.响应数据
        return sysCompanyUserList;
    }

    @Autowired
    @Lazy
    private SysDepartmentService sysDepartmentService;

    /*接口为/members的业务层*/
    @Override
    public PageResult pageFindAll(Long page, Long pageSize, Long departmentId, String keyword) {
        //判断是否登陆
        UserInfo userInfo = CurrentUserHolder.get();
        if (userInfo == null) {
            throw new NcException(ResponseEnum.UNAUTHORIZED);
        }
        //拼接构造分页条件
        ArrayList<Long> departmentIdList  = new ArrayList<>();
        sysDepartmentService.departmentIdList(departmentIdList, departmentId);
        if (departmentIdList.isEmpty()) {
            throw new NcException(ResponseEnum.DATA_NOT_EXISTS);
        }
        Page<SysCompanyUser> sysCompanyUserPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<SysCompanyUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysCompanyUser::getDepartmentId, departmentIdList);
        queryWrapper.eq(SysCompanyUser::getCompanyId, userInfo.getCompanyId());
        queryWrapper.eq(SysCompanyUser::getEnable, 1);
        PageResult<SysCompanyUser> pageResult = new PageResult<>();
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(w-> w.like(SysCompanyUser::getUserName, keyword).or()
                    .like(SysCompanyUser::getMobile, keyword).or()
                    .like(SysCompanyUser::getUserId, Long.valueOf(keyword))
            );
            return getPageResult(sysCompanyUserPage, queryWrapper, pageResult);
        }
        return getPageResult(sysCompanyUserPage, queryWrapper, pageResult);
    }

    private PageResult getPageResult(Page<SysCompanyUser> sysCompanyUserPage, LambdaQueryWrapper<SysCompanyUser> queryWrapper, PageResult<SysCompanyUser> pageResult) {
        Page<SysCompanyUser> page = this.page(sysCompanyUserPage, queryWrapper);
        List<SysCompanyUser> records = page.getRecords();
        pageResult.setRows(records);
        pageResult.setTotal(page.getTotal());
        pageResult.setTotalPage(page.getPages());
        return pageResult;
    }

    /*接口为/simpleList的业务层*/
    @Override
    public PageResult FindAll(Long page, Long pageSize, Long includeMember) {
        //判断是否登陆
        UserInfo userInfo = CurrentUserHolder.get();
        if (userInfo == null) {
            throw new NcException(ResponseEnum.UNAUTHORIZED);
        }
        //拼接构造分页查询所有条件
        List<SysDepartment> departmentList = sysDepartmentService.findAllDept();
        if (departmentList.isEmpty()) {
            throw new NcException(ResponseEnum.DATA_NOT_EXISTS);
        }
        Page<SysCompanyUser> sysCompanyUserPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<SysCompanyUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysCompanyUser::getDepartmentId, departmentList);
        queryWrapper.eq(SysCompanyUser::getCompanyId, includeMember);
        queryWrapper.eq(SysCompanyUser::getEnable, 1);
        PageResult<SysCompanyUser> pageResult = new PageResult<>();
        return getPageResult(sysCompanyUserPage, queryWrapper, pageResult);
    }

    /**
     * 对应  uploadexcel
     * @param excelFile
     */
    @Override
    public void uploadUser(MultipartFile excelFile) {

        if (excelFile.equals("") || excelFile.getSize() <= 0) {
            throw new NcException(ResponseEnum.FILE_NOT_FOUND);
        }

        try {
            EasyExcel.read(excelFile.getInputStream(), Emp.class, new EmpParseListener(this)).sheet(0).doRead();

        } catch (IOException e) {
           throw new NcException(ResponseEnum.DATA_TRANSFER_ERROR);
        }
    }

    @Autowired
    private SysUserService sysUserService;
    //D. 保存系统用户数据
    //​		需要做校验, 判定手机号、邮箱是否已经被注册； 判定企业员工工号是否被占用；
    //​	E. 保存企业员工数据
    //​	F. 维护企业员工关联的角色
    public void saveUser(List<Emp> list){
        ArrayList<String> mobileList = new ArrayList<>();//手机号集合
        ArrayList<String> emailList = new ArrayList<>();//邮箱集合
        ArrayList<String> workNumList = new ArrayList<>();//工号集合
        list.forEach(emp ->
                mobileList.add( emp.getMobile())
        );
        list.forEach(emp ->
                emailList.add( emp.getEmail())
        );
        list.forEach(emp ->
                workNumList.add( emp.getWorkNumber())
        );
        //判断工号是否存在
        LambdaQueryWrapper<SysCompanyUser> sysCompanyUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysCompanyUserLambdaQueryWrapper.in(SysCompanyUser::getWorkNumber, workNumList);
        int count = this.count(sysCompanyUserLambdaQueryWrapper);
        if (count>0){
            throw new NcException(ResponseEnum.WROK_NUM_EXISTS);
        }
        //判断手机号或邮箱是否存在
        LambdaQueryWrapper<SysUser> userLambdaQueryWrapper  = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.in(SysUser::getMobile,mobileList).or().in(SysUser::getEmail,emailList);
        int count1 = sysUserService.count(userLambdaQueryWrapper);
        if (count1>0){
            throw new NcException(ResponseEnum.USER_MOBILE_EMAIL_EXISTS);
        }
        //遍历集合添加将数据加入user表中
        for (Emp emp : list) {
            SysUser sysUser = getSysUser(emp);
            sysUserService.save(sysUser);
            SysCompanyUser sysCompanyUser = getSysCompanyUser(emp, sysUser);
            this.save(sysCompanyUser);
        }

    }
    //获取sysUser
    private SysUser getSysUser(Emp emp){
        SysUser sysUser = new SysUser();
        sysUser.setUsername( emp.getName());
        sysUser.setPassword(new BCryptPasswordEncoder().encode("123456"));
        sysUser.setMobile(emp.getMobile());
        sysUser.setEmail(emp.getEmail());
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        sysUser.setStatus((short)1);
        sysUser.setLastLoginCompanyId(CurrentUserHolder.get().getCompanyId());
        return sysUser;
    }
    //获取SysCompanyUse
    private SysCompanyUser getSysCompanyUser(Emp emp,SysUser sysUser) {
        SysCompanyUser sysCompanyUser = new SysCompanyUser();
        sysCompanyUser.setUserId(sysUser.getId());
        sysCompanyUser.setCompanyId(CurrentUserHolder.get().getCompanyId());
        sysCompanyUser.setCompanyName(CurrentUserHolder.get().getCompanyName());
        sysCompanyUser.setPost(emp.getPost());
        sysCompanyUser.setMobile(emp.getMobile());
        sysCompanyUser.setWorkNumber(emp.getWorkNumber());
        sysCompanyUser.setOfficeAddress(emp.getOfficeAddress());
        sysCompanyUser.setCreateTime(new Date());
        sysCompanyUser.setUpdateTime(new Date());
        sysCompanyUser.setUserName(emp.getName());
        sysCompanyUser.setEnable((short)1);
        sysCompanyUser.setEmail(emp.getEmail());
        return sysCompanyUser;
    }






}